//
//  AuctionTreasureVC.m
//  MyNewProject
//
//  Created by 王春辉 on 2020/1/4.
//  Copyright © 2020年 sun. All rights reserved.
//

#import "AuctionTreasureVC.h"
#import "AuctionTreasureTableViewCell.h"
#import "StoreHomePageVC.h"
#import "AuctionProductDetailVC.h"
#import "WJPasswordView.h"

#pragma mark -- mark 数据相关
#import "AuctionShopModel.h"
#import "ProductModel.h"

@interface AuctionTreasureVC ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate> {
    int _page;
    BOOL _firstLoad;
}
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSArray <AuctionShopDataModel *>* dataArray;
@property (nonatomic, copy) NSString *searchKey;
@end
static NSString *const identifier = @"auction_treasure_cell_id";
@implementation AuctionTreasureVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.gk_navTitle = @"精品拍场";
    self.gk_navBackgroundColor = SKClearColor;
    self.view.backgroundColor = SKColorWithHex(0xF7F7F7);
    _firstLoad = true;
    [self initContentViews];
    [self requestData];
}

- (void)initContentViews {
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.mas_offset(SKTopBar_Height);
        make.height.mas_equalTo(self.textField.mas_width).multipliedBy(42.0/345);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.textField);
        make.top.mas_equalTo(self.textField.mas_bottom).mas_offset(15);
        make.bottom.mas_offset(-SKBottomSafe_Height);
    }];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestData)];
    self.tableView.mj_footer = [MJRefreshBackStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestMoreData)];
}


#pragma mark -- mark 懒加载

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.showsVerticalScrollIndicator = false;
        _tableView.showsHorizontalScrollIndicator = false;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = self.view.backgroundColor;
        _tableView.tableFooterView = [UIView new];
        _tableView.tableHeaderView = [UIView new];
        [_tableView registerClass:[AuctionTreasureTableViewCell class] forCellReuseIdentifier:identifier];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
- (UITextField *)textField {
    if (!_textField) {
        _textField = [[UITextField alloc] init];
        _textField.placeholder = @"请输入您要搜索的商家";
        _textField.textColor = SKColorWithHex(0x333333);
        _textField.backgroundColor = [UIColor whiteColor];
        _textField.font = SKFONT_SIZE(16);
        _textField.layer.masksToBounds = true;
        _textField.layer.cornerRadius = 4.0;
        _textField.leftViewMode = UITextFieldViewModeAlways;
        _textField.delegate = self;
        _textField.returnKeyType = UIReturnKeySearch;
        [self.view addSubview:_textField];
        UIView *leftView = [[UIView alloc] init];
        leftView.backgroundColor = [UIColor whiteColor];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:SKIMAGE_NAMED(@"shop_search_btn_img")];
        [leftView addSubview:imageView];
        leftView.frame = CGRectMake(0, 0, 42.0 / 375 * self.view.width, 42.0/375 * self.view.width);
        imageView.frame = CGRectMake(10, 10, leftView.width - 20, leftView.height - 20);
        _textField.leftView = leftView;
    }
    return _textField;
}

#pragma mark -- mark UITableViewDelegate UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AuctionTreasureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    AuctionShopDataModel *model = self.dataArray[indexPath.row];
    cell.backgroundColor = tableView.backgroundColor;
    [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:model.img] placeholderImage:SKIMAGE_NAMED(@"cell_default_img")];
    cell.title = model.name ? model.name : @" ";
    cell.detail = (model.sell_count > 0) ? [NSString stringWithFormat:@"%d件商品正在售卖", model.sell_count] : @" ";
    cell.dataArray = model.sell;
    SKWeakSelf;
    cell.countDownEndBlock = ^{
        [weakSelf requestData];
    };
    cell.enterShopButtonClickBlock = ^{
        [weakSelf cellEndShopButtonClickBlockWith:indexPath];
    };
    cell.cellDidSelectBlock = ^(NSInteger index) {
        [weakSelf cellDidSelectedOnIndexPath:[NSIndexPath indexPathForRow:index inSection:indexPath.row]];
    };
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.view.width / 345 * 181 + 10;
}

#pragma mark -- mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.text.length > 0) {
        self.searchKey = textField.text;
        [self requestData];
        [self.view endEditing:true];
        return true;
    }else {
        return false;
    }
}

#pragma mark -- mark 业务逻辑

- (void)cellEndShopButtonClickBlockWith:(NSIndexPath *)indexPath {
    AuctionShopDataModel *model = self.dataArray[indexPath.row];
    if (model.pass.length > 0) {
        SKWeakSelf;
        [WJPasswordView showPasswordView:^(NSString * _Nonnull password) {
            if ([password isEqualToString:model.pass]) {
                StoreHomePageVC *vc = [[StoreHomePageVC alloc] init];
                vc.shopId = model.ID;
                [weakSelf.navigationController pushViewController:vc animated:true];
            }else {
                [weakSelf showMessage:@"密码错误，请重试～"];
            }
        } CompleteHanlder:nil];
    }else {
        StoreHomePageVC *vc = [[StoreHomePageVC alloc] init];
        vc.shopId = model.ID;
        [self.navigationController pushViewController:vc animated:true];
    }
}

/**
 点击某个商品

 @param indexPath indexPath
 */
- (void)cellDidSelectedOnIndexPath:(NSIndexPath *)indexPath {
    AuctionShopDataModel *model = self.dataArray[indexPath.section];
    AuctionSellDataModel *data = model.sell[indexPath.row];
    SKWeakSelf;
    [WJPasswordView showPasswordView:^(NSString * _Nonnull password) {
        if ([password isEqualToString:model.pass]) {
            AuctionProductDetailVC *vc = [[AuctionProductDetailVC alloc] init];
            vc.sellId = data.ID;
            vc.showType = AuctionProductDetailTypeDetail;
            [self.navigationController pushViewController:vc animated:YES];
        }else {
            [weakSelf showMessage:@"密码错误，请重试～"];
        }
    } CompleteHanlder:nil];
}

#pragma mark -- mark 获取网络数据

- (void)requestData {
    _page = 1;
    SKWeakSelf;
    [self requestRemoteDataWithPage:_page Complete:^(NSArray<AuctionShopDataModel *> *models) {
        weakSelf.dataArray = models;
        [weakSelf.tableView reloadData];
        [kCountDownManager reload];
    }];
}

- (void)requestMoreData {
    if (_page == 0) {
        return; }
    _page += 1;
    SKWeakSelf;
    [self requestRemoteDataWithPage:_page Complete:^(NSArray<AuctionShopDataModel *> *models) {
        NSMutableArray <AuctionShopDataModel *>* mArr = [NSMutableArray<AuctionShopDataModel *> arrayWithArray:weakSelf.dataArray];
        [mArr addObjectsFromArray:models];
        weakSelf.dataArray = mArr;
        [weakSelf.tableView reloadData];
        [kCountDownManager reload];
    }];
}

/// 获取数据
/// @param page page
/// @param complete complete
- (void)requestRemoteDataWithPage:(int)page Complete:(void(^)(NSArray <AuctionShopDataModel *>*))complete {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param addEntriesFromDictionary:@{@"page":@(page)}];
    if (self.searchKey) {
        [param addEntriesFromDictionary:@{@"":self.searchKey}];
    }
    SKWeakSelf;
    [YQNetworking getWithUrl:@"Shop/getshopList" params:param reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        AuctionShopModel *model = [AuctionShopModel modelWithDictionary:response];
        if ([model isSuccess]) {
            if (complete) {
                NSMutableArray <AuctionShopDataModel *>* mArr = [NSMutableArray<AuctionShopDataModel *> array];
                for (AuctionShopDataModel *shop in model.data) {
                    if (shop.sell.count > 0) {
                        [mArr addObject:shop];
                    }
                }
                complete(mArr); }
        }else {
            [weakSelf showMessage:model.msg];
        }
        [weakSelf endRefreshing];
    } failBlock:^(NSError *error) {
        [weakSelf debugShowMessage:error.localizedDescription];
        [weakSelf endRefreshing];
    }];
}

- (void)endRefreshing {
    if ([self.tableView.mj_header isRefreshing]) {
        [self.tableView.mj_header endRefreshing];
    }
    if ([self.tableView.mj_footer isRefreshing]) {
        [self.tableView.mj_footer endRefreshing];
    }
}


@end
